package com.liu.permission.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.permission.entity.base.PermissionInfo;
import com.liu.permission.mapper.PermissionInfoMapper;
import com.liu.permission.service.IPermissionInfoService;
import com.liu.user.entity.base.UserPermissionInfo;
import com.liu.user.service.IUserPermissionInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.transaction.Transactional;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LiuChengLong
 * @since 2022-09-22
 */
@Service
@Slf4j
public class PermissionInfoServiceImpl extends ServiceImpl<PermissionInfoMapper, PermissionInfo> implements IPermissionInfoService {

    @Resource
    private IUserPermissionInfoService userPermissionInfoService;

    @Override
    public Boolean checkPermissionCodeExistence(String permissionCode) {
        String isExistence = baseMapper.getByPermissionCode(permissionCode);
        return isExistence == null;
    }

    @Override
    @Transactional
    public boolean save(PermissionInfo permissionInfo){
        try {
            // 插入权限表
            baseMapper.insert(permissionInfo);
            // 获取当前新增权限的id
            Map<String, Object> map = new HashMap<>();
            map.put("permission_code", permissionInfo.getPermissionCode());
            PermissionInfo info = baseMapper.selectByMap(map).get(0);
            // 新增权限时，自动给admin用户添加权限
            UserPermissionInfo userPermissionInfo = new UserPermissionInfo();
            userPermissionInfo.setUserId(1);
            userPermissionInfo.setPermissionId(info.getId());
            userPermissionInfo.setCreateBy(1);
            userPermissionInfoService.save(userPermissionInfo);
            return true;
        } catch (Exception e){
            log.error("添加权限失败：{}", e.getMessage(), e);
            return false;
        }
    }
}
